package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.serve.dto.CheckInApplyDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

import static java.time.Period.between;

/**
 * 入住Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1,查询老人信息,判断当前老人的状态,当为已入住的时候直接返回/报异常
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getStatus,1).eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));
        if(!ObjectUtils.isEmpty(elder)){
            throw new BaseException("老人已入住");
        }
        //2,更新床位信息
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(startDate)) {
            bed.setBedStatus(2);
        } else if (now.isAfter(startDate)) {
            bed.setBedStatus(1);
        }
        bedMapper.updateById(bed);
        //3,新增或者更改老人
        elder = insertOrUpdateElderInfo(bed, checkInApplyDto);
        //4,新增签约办理
        insertContract(elder,checkInApplyDto);
        //新增入住信息
        CheckIn checkIn = insertCheckInInfo(elder, checkInApplyDto);
        //新增入住配置
        insertCheckInConfig(checkIn,checkInApplyDto);
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        //查询信息
        //创建返回对象
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //老人响应信息
        CheckIn checkIn = checkInMapper.selectById(id);
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        if(elder==null){
            return null;
        }
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder,checkInElderVo);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate parse = LocalDate.parse(elder.getBirthday(), dateTimeFormatter);
        checkInElderVo.setAge(between(parse, LocalDate.now()).getYears());
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //家属响应信息
        String remark = checkIn.getRemark();
        if(remark!=null){
            List<ElderFamilyVo> elderFamilyVos = JSON.parseArray(remark, ElderFamilyVo.class);
            checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        }
        //入住配置响应信息
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        if (checkInConfig!=null) {
            BeanUtils.copyProperties(checkInConfig,checkInConfigVo);
        }
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        //签约办理相应信息
        checkInDetailVo.setContract(contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId,elder.getId())));
        return checkInDetailVo;
    }

    private void insertCheckInConfig(CheckIn checkIn, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn insertCheckInInfo(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void insertContract(Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(),contract);
        String contractNo = "HT"+CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        contract.setElderId(Integer.valueOf(elder.getId()+""));
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    private Elder insertOrUpdateElderInfo(Bed bed, CheckInApplyDto checkInApplyDto) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(),elder);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        Elder elderTarget = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elder.getIdCardNo()).eq(Elder::getStatus, 1));
        if(ObjectUtils.isEmpty(elderTarget)){
            //新增
            elderMapper.insert(elder);
        }else{
            //修改
            elderMapper.updateElder(elder);
        }
        return elder;
    }
}
